package org.warehouse.dao.impl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;

import org.warehouse.dao.IDao;
import org.warehouse.dao.engine.DaoException;
import org.warehouse.dao.engine.DbExecutor;

public abstract class AbstractDao implements IDao {
	
	private DbExecutor dbExecutor = DbExecutor.getInstance();

	private final AtomicInteger index;
	
	private final Logger logger = Logger.getLogger(getClass().getSimpleName());
	
	protected AbstractDao() {
		index = new AtomicInteger(getCurrentIndex());
    }

	public abstract String getTableName();
	
	protected final Logger getLogger() {
		return logger;
	}
	
	protected final Integer getCurrentIndex() {
	    String sql = MessageFormat.format("SELECT MAX({0}) FROM {1}", getIndexColumnName(), getTableName());
	    PreparedStatement ps = getDbExecutor().getPreparedStatement(sql);
	    ResultSet rs = getDbExecutor().invoke(ps);
	    try {
	        if (!rs.next()) {
	        	return 0;
	        } else {
	        	return rs.getInt(MessageFormat.format("MAX({0})", getIndexColumnName()));
	        }
        } catch (SQLException e) {
	        throw new DaoException(e);
        } finally {
        	getDbExecutor().closePreparedStatement(ps);
        }
	}
	
	protected final Integer getNewIndex() {
		return index.incrementAndGet();
	}
	
	protected final DbExecutor getDbExecutor() {
		return dbExecutor;
	}
	
}
